/**
 * Role Manager - Handles UI modifications based on user role
 */
document.addEventListener('DOMContentLoaded', function() {
    console.log('RoleManager: Initializing role-based UI modifications');
    
    // Get user data from sessionStorage
    const userDataStr = sessionStorage.getItem('user');
    if (!userDataStr) {
        console.error('No user data found in sessionStorage');
        window.location.href = '/auth/login';
        return;
    }
    
    try {
        const userData = JSON.parse(userDataStr);
        const userRole = userData.role;
        
        // Update user name display
        const userNameElements = document.querySelectorAll('.user-name');
        userNameElements.forEach(element => {
            element.textContent = `欢迎，${userData.username || '用户'}`;
        });
        
        console.log('User role:', userRole);
        
        // Apply role-specific UI modifications
        if (userRole === 'DOCTOR') {
            applyDoctorRoleUI();
        } else if (userRole === 'PATIENT') {
            applyPatientRoleUI();
        } else {
            console.log('Standard user role detected, no specific UI modifications needed');
        }
        
    } catch (error) {
        console.error('Error parsing user data:', error);
    }
});

/**
 * Apply UI modifications for Doctor role
 */
function applyDoctorRoleUI() {
    console.log('Applying doctor role UI modifications');
    
    // Hide the health monitoring module from navigation
    const monitorNavItem = document.querySelector('.nav-item[data-page="monitor"]');
    if (monitorNavItem) {
        monitorNavItem.style.display = 'none';
    }
    
    // Add patient management module to navigation if it doesn't exist
    const navList = document.querySelector('.nav-list');
    const newsNavItem = document.querySelector('.nav-item[data-page="news"]');
    const existingPatientManagementItem = document.querySelector('.nav-item[data-page="patient-management"]');
    
    if (navList && newsNavItem && !existingPatientManagementItem) {
        const patientManagementItem = document.createElement('li');
        patientManagementItem.className = 'nav-item';
        patientManagementItem.setAttribute('data-page', 'patient-management');
        patientManagementItem.innerHTML = `
            <a href="#"><i class="fas fa-user-injured"></i>患者管理</a>
        `;
        
        // Insert the patient management item after the news item
        navList.insertBefore(patientManagementItem, newsNavItem.nextSibling);
    }
    
    // Add the click event listener to navigation items if not already set
    addNavigationEventListeners();
}

/**
 * Apply UI modifications for Patient role
 */
function applyPatientRoleUI() {
    console.log('Applying patient role UI modifications');
    
    // Hide the patient management section for patients
    const patientManagementNavItem = document.querySelector('.nav-item[data-page="patient-management"]');
    if (patientManagementNavItem) {
        patientManagementNavItem.style.display = 'none';
    }
    
    // Hide the patient management page 
    const patientManagementPage = document.getElementById('patient-management');
    if (patientManagementPage) {
        patientManagementPage.style.display = 'none';
    }
    
    // Add the click event listener to navigation items if not already set
    addNavigationEventListeners();
}

/**
 * Add click event listeners to all navigation items
 */
function addNavigationEventListeners() {
    const navItems = document.querySelectorAll('.nav-item');
    
    navItems.forEach(item => {
        // Skip if it's the logout item or already has a click event
        if (item.dataset.page === 'logout') {
            if (!item.hasClickListener) {
                item.hasClickListener = true;
                item.addEventListener('click', function(e) {
                    e.preventDefault();
                    logout(); // This function is defined in auth.js
                });
            }
            return;
        }
        
        // Skip if it already has a click listener
        if (item.hasClickListener) {
            return;
        }
        
        item.hasClickListener = true;
        item.addEventListener('click', function(e) {
            e.preventDefault();
            
            // Remove active class from all nav items
            navItems.forEach(navItem => {
                navItem.classList.remove('active');
            });
            
            // Add active class to the clicked nav item
            this.classList.add('active');
            
            // Hide all page content
            document.querySelectorAll('.page-content').forEach(page => {
                page.style.display = 'none';
            });
            
            // Show the corresponding page content
            const pageId = this.dataset.page;
            const pageContent = document.getElementById(pageId);
            if (pageContent) {
                pageContent.style.display = 'block';
            }
        });
    });
} 